﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using KPIS.GERP.GIMS.DAL;
using System.Data;
using System.IO;

namespace KPIS.GERP.GIMS.APP.APP_UI.Add_Form
{
    public partial class ICM_Receive : System.Web.UI.Page
    {
        Common.Main cn = new Common.Main();
        CommandControl cmdFac = new CommandControl();
        private MasterDepreciationTypeDAL d_masdep_type = new MasterDepreciationTypeDAL();
        private ReceiveBLL bll = new ReceiveBLL();
        private ResourceMasterTypeBLL masBLL = new ResourceMasterTypeBLL();
        private MasterWarehouseBLL whBLL = new MasterWarehouseBLL();
        private DeliveryNoteBLL dnBLL = new DeliveryNoteBLL();
        private HrmJobSiteBLL jsBLL = new HrmJobSiteBLL();
        private D_ReceiveType recTypeBLL = new D_ReceiveType();

        protected void Page_Load(object sender, EventArgs e)
        {
            ValidateControl();
            cbReceiveType.Attributes.Add("onclick", "return ChangeReceiveType('" + cbReceiveType.SelectedValue + "')");

            if (!IsPostBack)
            {
                LoadDataGrid();
            }
        }
        public void LoadDataGrid()
        {
            IList<M_IcmReceiveObject> info = bll.GetReceiveObject((int?)null);
            grdInventory.DataSource = info;
            grdInventory.DataBind();

            cmdFac.GridCommand(panelList, panelGrid, panelCommand);
        }
        public void ValidateControl()
        {
            rdoWH.Checked = true;
            rdoWH.Attributes.Add("onclick", "return CheckWareHouse('" + cmbWareHouse.ClientID + "', '" + cmbToJobSite.ClientID + "')");
            rdoJS.Attributes.Add("onclick", "return CheckJobSite('" + cmbWareHouse.ClientID + "', '" + cmbToJobSite.ClientID + "')");

        }

        protected void grdInventory_ItemCommand(object sender, GridCommandEventArgs e)
        {
        }
        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }
        public void GetKeyValue(string seq)
        {
            if (seq.Length > 0)
            {
                IList<M_IcmReceiveObject> infoList = bll.GetReceiveObject(Convert.ToInt32(seq));

                if (infoList.Count > 0)
                {
                    M_IcmReceiveObject info = infoList[0];

                    txtName.Text = info.icm_receive_name;
                    LoadReceiveType();
                    cbReceiveType.SelectedValue = info.receive_type_seq.ToString();
                    panelTransfer.Visible = cbReceiveType.SelectedValue != "2";

                    cmbDN.Items.Add(new RadComboBoxItem(info.icm_dn_code, info.icm_dn_seq.ToString()));
                    cmbDN.SelectedValue = info.icm_dn_seq.ToString();
                    cmbWareHouse.Items.Add(new RadComboBoxItem(info.icm_wh_name, info.icm_wh_seq.ToString()));
                    cmbWareHouse.SelectedValue = info.icm_wh_seq.ToString();
                    cmbToJobSite.Items.Add(new RadComboBoxItem(info.job_site_name, info.job_site_seq.ToString()));
                    cmbToJobSite.SelectedValue = info.job_site_seq.ToString();
                    cmbInventoryType.Items.Add(new RadComboBoxItem(info.icm_res_type_name, info.icm_res_type_seq.ToString()));
                    cmbInventoryType.SelectedValue = info.icm_res_type_seq.ToString();
                    txtReceiveDate.Text = info.receive_date.ToString();
                    txtFromTransfer.Text = "";
                    txtTranRefNo.Text = info.tranfer_ref_no;
                    txtRemark.Text = info.remark;

                    cmdFac.ViewCommand(panelList, panelGrid, panelCommand);
                }
            }
        }
        private string fnGen_ReceiveCode()
        {
            string strMonth = "";
            string strYear = "";
            string strRunning = "";
            string strReceiveCode = "";
            try
            {
                DataSet ListDataCommand = bll.GenReceiveCode();
                DataTable table = ListDataCommand.Tables[0];
                strYear = table.Rows[0]["YearValue"].ToString();
                strMonth = cn.ConvertstrMonth(table.Rows[0]["MonthValue"].ToString());
                strRunning = cn.ConvertstrRunningFiveDigit(table.Rows[0]["running"].ToString());
                strReceiveCode = "RC" + strYear + "-" + strMonth + "-" + strRunning;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return strReceiveCode;
        }
        public void LoadReceiveType()
        {
            cbReceiveType.DataSource = recTypeBLL.GetList();
            cbReceiveType.DataBind();
        }
        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            Session["ICM_RECEIVE_TYPE"] = cmbReceiveType.SelectedValue;
            //Close the active ToolTip.
            RadManager1.ResponseScripts.Add(@"CloseTooltip();");
            //ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "onclick", "CloseTooltip()", true);
            cmdFac.AddNewCommand(panelList, panelGrid, panelCommand);

            LoadReceiveType();
            cbReceiveType.SelectedValue = Session["ICM_RECEIVE_TYPE"].ToString();

            //ValidateControl();
        }
        private void LoadValiDateDetail()
        {
            //RequiredFieldValidator valJobSite = new RequiredFieldValidator();
            //valJobSite.ID = "ValcbJobSite";
            //valJobSite.ControlToValidate = "cbJobSite";
            //valJobSite.SetFocusOnError = true;
            //valJobSite.Display = ValidatorDisplay.Dynamic;
            //valJobSite.ErrorMessage = "* กรุณาระบุหน่วยงาน *";
            //panelValJobSite.Controls.Add(valJobSite);
            //RequiredFieldValidator valYearType = new RequiredFieldValidator();
            //valYearType.ID = "ValcbYearType";
            //valYearType.ControlToValidate = "cbYearType";
            //valYearType.SetFocusOnError = true;
            //valYearType.Display = ValidatorDisplay.Dynamic;
            //valYearType.ErrorMessage = "* กรุณาระบุประเภทปี *";
            //panelValYearType.Controls.Add(valYearType);
            //RequiredFieldValidator valYear = new RequiredFieldValidator();
            //valYear.ID = "ValtxtYear";
            //valYear.ControlToValidate = "txtYear";
            //valYear.SetFocusOnError = true;
            //valYear.Display = ValidatorDisplay.Dynamic;
            //valYear.ErrorMessage = "* กรุณาระบุปี *";
            //panelValYear.Controls.Add(valYear);
            //RequiredFieldValidator valPurchaseType = new RequiredFieldValidator();
            //valPurchaseType.ID = "ValcbPurchaseType";
            //valPurchaseType.ControlToValidate = "cbPurchaseType";
            //valPurchaseType.SetFocusOnError = true;
            //valPurchaseType.Display = ValidatorDisplay.Dynamic;
            //valPurchaseType.ErrorMessage = "* กรุณาระบุประเภทการจัดหา *";
            //panelValPurchaseType.Controls.Add(valPurchaseType);
            //RequiredFieldValidator valDate = new RequiredFieldValidator();
            //valDate.ID = "ValtxtDate";
            //valDate.ControlToValidate = "txtDate";
            //valDate.SetFocusOnError = true;
            //valDate.Display = ValidatorDisplay.Dynamic;
            //valDate.ErrorMessage = "* กรุณาระบุวันที่รายการ *";
            //panelValDate.Controls.Add(valDate);
            //CustomValidator valCustomDate = new CustomValidator();
            //valCustomDate.ID = "ValCustomDate";
            //valCustomDate.ControlToValidate = "txtDate";
            //valCustomDate.SetFocusOnError = true;
            //valCustomDate.Display = ValidatorDisplay.Dynamic;
            //valCustomDate.ErrorMessage = "* กรุณาระบุวันที่ให้ถูกต้อง *";
            //valCustomDate.ClientValidationFunction = "validateDate";
            //panelValDate.Controls.Add(valCustomDate);
            //RequiredFieldValidator valName = new RequiredFieldValidator();
            //valName.ID = "ValtxtName";
            //valName.ControlToValidate = "txtName";
            //valName.SetFocusOnError = true;
            //valName.Display = ValidatorDisplay.Dynamic;
            //valName.ErrorMessage = "* กรุณาระบุเรื่อง *";
            //panelValName.Controls.Add(valName);
            //CustomValidator valCustomDateReq = new CustomValidator();
            //valCustomDateReq.ID = "ValCustomDateReq";
            //valCustomDateReq.ControlToValidate = "txtDateReq";
            //valCustomDateReq.SetFocusOnError = true;
            //valCustomDateReq.Display = ValidatorDisplay.Dynamic;
            //valCustomDateReq.ErrorMessage = "* กรุณาระบุวันที่ให้ถูกต้อง *";
            //valCustomDateReq.ClientValidationFunction = "validateDate";
            //panelValDateReq.Controls.Add(valCustomDateReq);
        }
        protected void AddNew_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList, panelGrid, panelCommand);
        }

        protected void Edit_Click(object sender, EventArgs e)
        {
            //GetKeyValue(hdSeq.ToString());
            cmdFac.EditCommand(panelList, panelGrid, panelCommand);
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            IList<M_IcmReceiveObject> infoList = new List<M_IcmReceiveObject>();
            if (panelGrid.Visible)
            {
                //int Sequence = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["icm_receive_seq"]);
                //bll.Delete(Sequence, Int32.Parse(Session["EmpSeq"].ToString()));
            }
            else
            {
                bll.Delete(Convert.ToInt32(hdSeq.Value), Int32.Parse(Session["EmpSeq"].ToString()));
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            LoadDataGrid();
        }

        protected void AddNewSave_Click(object sender, EventArgs e)
        {
            M_IcmReceiveObject m_receive = new M_IcmReceiveObject();

            m_receive.icm_receive_name = txtName.Text.Trim();
            m_receive.icm_receive_code = fnGen_ReceiveCode();
            m_receive.icm_dn_seq = Convert.ToInt32(cmbDN.SelectedValue);
            m_receive.icm_wh_seq = cn.ConvertNullInt(cmbWareHouse.SelectedValue);
            m_receive.job_site_seq = cn.ConvertNullInt(cmbToJobSite.SelectedValue);
            m_receive.icm_res_type_seq = Convert.ToInt32(cmbInventoryType.SelectedValue);
            m_receive.receive_type_seq = cn.ConvertNullInt(cmbReceiveType.SelectedValue);
            m_receive.receive_date = cn.ConvertNullDateTime(txtReceiveDate.TextWithLiterals);
            m_receive.tranfer_ref_no = txtTranRefNo.Text.Trim();
            m_receive.created_by = Convert.ToInt32(Session["EmpSeq"].ToString());

            if (ValtxtName.IsValid == false)
            {
                return;
            }

            try
            {
                bll.Insert(m_receive);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
            cmdFac.ViewCommand(panelList, panelGrid, panelCommand);
            LoadDataGrid();
        }

        protected void EditSave_Click(object sender, EventArgs e)
        {
            M_IcmReceiveObject m_receive = new M_IcmReceiveObject();

            m_receive.icm_receive_seq = Convert.ToInt32(hdSeq.Value);
            m_receive.icm_receive_name = txtName.Text.Trim();
            m_receive.icm_receive_code = fnGen_ReceiveCode();
            m_receive.icm_dn_seq = Convert.ToInt32(cmbDN.SelectedValue);
            m_receive.icm_wh_seq = cn.ConvertNullInt(cmbWareHouse.SelectedValue);
            m_receive.job_site_seq = cn.ConvertNullInt(cmbToJobSite.SelectedValue);
            m_receive.icm_res_type_seq = Convert.ToInt32(cmbInventoryType.SelectedValue);
            m_receive.receive_type_seq = cn.ConvertNullInt(cmbReceiveType.SelectedValue);
            m_receive.receive_date = cn.ConvertNullDateTime(txtReceiveDate.TextWithLiterals);
            m_receive.tranfer_ref_no = txtTranRefNo.Text.Trim();
            m_receive.updated_by = Convert.ToInt32(Session["EmpSeq"].ToString());

            //if (ValtxtName.IsValid == false)
            //{
            //    return;
            //}

            try
            {
                bll.Update(m_receive);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
            cmdFac.ViewCommand(panelList, panelGrid, panelCommand);
        }

        protected void Cancel_Click(object sender, EventArgs e)
        {
            cmdFac.CancelCommand(panelList, panelGrid, panelCommand);
        }

        protected void ShowGrid_Click(object sender, EventArgs e)
        {
            LoadDataGrid();
        }

        protected void Grid_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "DataDelete")
            {
                int Sequence = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["icm_receive_seq"]);

                bll.Delete(Sequence, Int32.Parse(Session["EmpSeq"].ToString()));
            }
            LoadDataGrid();
        }

        protected void RadManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            GetKeyValue(e.Argument);
        }

        protected void OnAjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            RadAjaxPanel1.Controls.Add(Page.LoadControl("../UserControl/Personal_Data.ascx"));
        }

        protected void clearFilter_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in grdInventory.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            grdInventory.MasterTableView.FilterExpression = string.Empty;
            LoadDataGrid();
        }
        protected void cmbReceiveType_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            // By KHIM *********************************************
            IList<M_ReceiveType> infoList = recTypeBLL.GetList();

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbReceiveType.Items.Add(new RadComboBoxItem(infoList[i].receive_type_name, infoList[i].receive_type_seq.ToString()));

                TableRow tr = new TableRow();

                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].receive_type_name;
                tdName.Width = Unit.Pixel(250);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                ((Table)cmbReceiveType.Items[j].FindControl("tableReceiveType")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }
        protected void cmbDN_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            // By KHIM *********************************************
            IList<DeliveryNoteInfo> infoList = dnBLL.GetDeliveryNote((int?)null, (int?)null, (int?)null, (int?)null, (int?)null, SystemInfo._ApproveRecordStatus);

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbDN.Items.Add(new RadComboBoxItem(infoList[i].RefNo + "(" + infoList[i].Name + ")", infoList[i].Seq.ToString()));

                TableRow tr = new TableRow();

                TableCell tdRefNo = new TableCell();
                Label lblRefNo = new Label();
                lblRefNo.Text = infoList[i].RefNo;
                tdRefNo.Width = Unit.Pixel(100);
                tdRefNo.Controls.Add(lblRefNo);
                tr.Cells.Add(tdRefNo);

                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(250);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);

                TableCell tdDnDate = new TableCell();
                Label lblDnDate = new Label();
                lblDnDate.Text = infoList[i].DeliveryDate.ToString();
                tdDnDate.Width = Unit.Pixel(100);
                tdDnDate.Controls.Add(lblDnDate);
                tr.Cells.Add(tdDnDate);

                ((Table)cmbDN.Items[j].FindControl("tableDN")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }
        protected void cmbWareHouse_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            // By KHIM *********************************************
            IList<MasterWarehouseInfo> infoList = whBLL.GetMasterWarehouse();

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbWareHouse.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));

                TableRow tr = new TableRow();

                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(250);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                ((Table)cmbWareHouse.Items[j].FindControl("tableWareHouse")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }
        protected void cmbToJobSite_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            // By KHIM *********************************************
            IList<HrmJobSiteInfo> infoList = jsBLL.GetJobSite(e.Text);

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbToJobSite.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));

                TableRow tr = new TableRow();

                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(250);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                ((Table)cmbToJobSite.Items[j].FindControl("tableToJobSite")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }
        protected void cmbInventoryType_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            // By KHIM *********************************************
            IList<ResourceMasterTypeInfo> infoList = masBLL.GetResourceMasterType();

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbInventoryType.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));

                TableRow tr = new TableRow();

                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(250);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                ((Table)cmbInventoryType.Items[j].FindControl("tableInventoryType")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }
        protected void cmbDpType_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            // ประเภทค่าเสื่อม
            //IList<MasterDepreciationTypeInfo> infoList = d_masdep_type.GetMasterDepreciationType();
            //int itemOffset = e.NumberOfItems;
            //int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            //e.EndOfItems = (endOffset == infoList.Count);
            //int j = 0;
            //for (int i = itemOffset; i < endOffset; i++)
            //{
            //    cmbDpType.Items.Add(new RadComboBoxItem(infoList[i].Name.ToString(), infoList[i].Seq.ToString()));
            //    TableRow tr = new TableRow();
            //    TableCell tdCode = new TableCell();
            //    Label lblCode = new Label();
            //    lblCode.Text = infoList[i].Seq.ToString();
            //    tdCode.Width = Unit.Pixel(30);
            //    tdCode.Controls.Add(lblCode);
            //    tr.Cells.Add(tdCode);
            //    TableCell tdName = new TableCell();
            //    Label lblName = new Label();
            //    lblName.Text = infoList[i].Name;
            //    tdName.Width = Unit.Pixel(380);
            //    tdName.Controls.Add(lblName);
            //    tr.Cells.Add(tdName);
            //    ((Table)cmbDpType.Items[j].FindControl("tableDpType")).Controls.Add(tr);
            //    j++;
            //}

            //e.Message = GetStatusMessage(endOffset, infoList.Count);

        }

    }
}
